package com.pphh.demo;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.*;

/**
 * Created by pphh on 2022/10/8.
 */
public class TestTtl2 {

    private TransmittableThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();

    private ExecutorService pool = new ThreadPoolExecutor(5, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue());
    private ExecutorService childPool;

    public void test() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        pool.submit(() -> {
            childPool = new ThreadPoolExecutor(5, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue());
            latch.countDown();
        });
        latch.await();

        Logger.logMessage("--");
        threadLocal.set("T1-root");
        for (Integer i = 0; i < 10; i++) {
            int index = i;
            childPool.submit(() -> {
                Logger.logMessage("子线程, value = " + threadLocal.get());
                threadLocal.set("T1-child-" + index);
                Logger.logMessage("子线程-after-set, value = " + threadLocal.get());
            });
        }

        Thread.sleep(1000);

        Logger.logMessage("--");
        threadLocal.set("T2-root2");
        for (Integer i = 0; i < 10; i++) {
            int index = i;
            Runnable runnable = TtlRunnable.get(() -> {
                Logger.logMessage("子线程, value = " + threadLocal.get());
                threadLocal.set("T2-child-" + index);
                Logger.logMessage("子线程-after-set, value = " + threadLocal.get());
            });
            childPool.submit(runnable);
        }

        pool.shutdown();
        childPool.shutdown();

    }

}
